package com.vfa.vocaburay;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.vfa.data.Question;

public class Quiz extends Activity implements View.OnClickListener {
    private TextView info;
    private int questionOrder = 0;
    private Question currentQuestion;
    private TextView question;
    private TextView timeCountDown;
    private Button nextButton;
    private Button preButton;
    private Button finButton;
    private RadioButton answer1;
    private RadioButton answer2;
    private RadioButton answer3;
    private RadioButton answer4;
    private RadioGroup radioGroup;
    private int score;
    private int totalTime;
    private Timer timerTask;
    private String userName;
    private String language;
    private int noOfQuestions;
    private int inputMethod;
    private String categoryId;
    private String quizName;
    ArrayList<Question> questionList = new ArrayList<Question>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // set layout
        setContentView(R.layout.quizlayout);
        // list of question
        Bundle bundle = getIntent().getExtras();
        noOfQuestions = bundle.getInt("question");
        userName = bundle.getString("userName");
        language = bundle.getString("language");
        inputMethod = bundle.getInt("inputMethod");
        categoryId = bundle.getString("categoryId");
        quizName  = bundle.getString("quizname");

        // 30s every questions
        totalTime = noOfQuestions * 30;
        questionList = vfaMain.wordData.getRandomDataBaseByTypeAndLanguage(inputMethod, language, noOfQuestions,categoryId,quizName);
        // create content
        if(questionList == null || questionList.size() == 0)
        {
        	Toast.makeText(getBaseContext(), "No have question with this Quiz Name ", Toast.LENGTH_SHORT).show();
        	finish();
        	return;
        }
        currentQuestion = questionList.get(0);

        // initialize
        question = (TextView) findViewById(R.id.textView1);
        radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
        answer1 = (RadioButton) findViewById(R.id.radio1);
        answer2 = (RadioButton) findViewById(R.id.radio2);
        answer3 = (RadioButton) findViewById(R.id.radio3);
        answer4 = (RadioButton) findViewById(R.id.radio4);
        nextButton = (Button) findViewById(R.id.button1);
        preButton = (Button) findViewById(R.id.button2);
        finButton = (Button) findViewById(R.id.button3);
        timeCountDown = (TextView) findViewById(R.id.countdown);
        timeCountDown.setTextColor(Color.BLUE);
        setQuestionContent();
        // set click listener
        answer1.setOnClickListener(radio_listener);
        answer2.setOnClickListener(radio_listener);
        answer3.setOnClickListener(radio_listener);
        answer4.setOnClickListener(radio_listener);
        nextButton.setOnClickListener(nextButton_listener);
        preButton.setOnClickListener(preButton_listener);
        finButton.setOnClickListener(finButton_listener);
        // set info
        info = (TextView) findViewById(R.id.textView2);
        new CountDown();
    }

    private OnClickListener radio_listener = new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            RadioButton rb = (RadioButton) v;
            if (rb.getText().toString()
                    .equals(currentQuestion.getRightAnswer())) {
                rb.setTextColor(Color.BLUE);
                // info.setText("Right answer !");
                ++score;
            } else {
                rb.setTextColor(Color.RED);
                // hightlight right anwser
                highLightRightAnwser();
            }
            // unclickable after choosing new anwser
            for (int i = 0; i < radioGroup.getChildCount(); i++) {
                radioGroup.getChildAt(i).setClickable(false);
            }
            // set question answered
            currentQuestion.setChosenAnswer(rb.getText().toString());
            currentQuestion.setAnwsered();

        }
    };
    private OnClickListener nextButton_listener = new OnClickListener() {
        public void onClick(View v) {
            // Perform action on clicks
            if (questionOrder == questionList.size() - 1) {

                info.setText("Click \"OK\" to finish the test");
                info.setTextColor(Color.RED);
                finButton.setVisibility(View.VISIBLE);
                // nextButton.setClickable(false);
                /*
                 * for (int i = 0; i < radioGroup.getChildCount(); i++) {
                 * radioGroup.getChildAt(i).setClickable(false); }
                 */
            }
            // neu con cau hoi
            else if (questionOrder < questionList.size() - 1) {
                currentQuestion = questionList.get(++questionOrder);
                setUpNewQuestion();
                setQuestionContent();
            }

        }
    };
    private OnClickListener preButton_listener = new OnClickListener() {
        public void onClick(View v) {
            if (questionOrder == 0) {
                // do nothing
            } else if (questionOrder > 0) {
                currentQuestion = questionList.get(--questionOrder);
                setUpNewQuestion();
                setQuestionContent();
            }
            info.setText("");
            finButton.setVisibility(View.INVISIBLE);
        }
    };
    private OnClickListener finButton_listener = new OnClickListener() {
        public void onClick(View v) {
            // disableSelection();
        	AlertDialog.Builder bd = new AlertDialog.Builder(Quiz.this);
			bd.setMessage("Are you sure you want to finish the test?").setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finishQuiz();
					
				}
			});
			bd.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
					
				}
			}).show();
            
        }
    };

    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

    private void setQuestionContent() {

        question.setText(questionOrder + 1 + ". "
                + currentQuestion.getQuestion());
        answer1.setText(currentQuestion.getAnswer1());
        answer2.setText(currentQuestion.getAnswer2());
        answer3.setText(currentQuestion.getAnswer3());
        answer4.setText(currentQuestion.getAnswer4());

        if (currentQuestion.alreadyAnwser() == true) {
            // unclickable after choosing new question
            for (int i = 0; i < radioGroup.getChildCount(); i++) {
                radioGroup.getChildAt(i).setClickable(false);
            }
            if (currentQuestion.getChosenAnwser().equals(
                    currentQuestion.getAnswer1()))
                answer1.setChecked(true);
            if (currentQuestion.getChosenAnwser().equals(
                    currentQuestion.getAnswer2()))
                answer2.setChecked(true);
            if (currentQuestion.getChosenAnwser().equals(
                    currentQuestion.getAnswer3()))
                answer3.setChecked(true);
            if (currentQuestion.getChosenAnwser().equals(
                    currentQuestion.getAnswer4()))
                answer4.setChecked(true);

        }
    }

    private void setUpNewQuestion() {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            radioGroup.getChildAt(i).setClickable(true);
            radioGroup.clearCheck();
            answer1.setTextColor(Color.WHITE);
            answer2.setTextColor(Color.WHITE);
            answer3.setTextColor(Color.WHITE);
            answer4.setTextColor(Color.WHITE);
            info.setText("");
        }
    }

    private void highLightRightAnwser() {
        if (answer1.getText().equals(currentQuestion.getRightAnswer()))
            answer1.setTextColor(Color.YELLOW);
        if (answer2.getText().equals(currentQuestion.getRightAnswer()))
            answer2.setTextColor(Color.YELLOW);
        if (answer3.getText().equals(currentQuestion.getRightAnswer()))
            answer3.setTextColor(Color.YELLOW);
        if (answer4.getText().equals(currentQuestion.getRightAnswer()))
            answer4.setTextColor(Color.YELLOW);
        
    }

    private void disableSelection() {
        for (int i = 0; i < radioGroup.getChildCount(); i++) {
            radioGroup.getChildAt(i).setClickable(false);
            radioGroup.clearCheck();
            info.setText("");
        }
    }

    @Override
    public void onBackPressed() {
        newWordDialog();
        // return;
    }

    private void newWordDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Quiz is on progress !").setCancelable(false)
                .setPositiveButton("Quit",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                timerTask.cancel();
                                Quiz.this.finish();
                            }
                        }).setNegativeButton("Back to Quiz",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void finishQuiz() {
        timerTask.cancel();
        Intent intent = new Intent(Quiz.this, Result.class);
        intent.putExtra("totalQuestion", questionList.size()).putExtra(
                "rightQuestion", score);
        startActivity(intent);
        Quiz.this.finish();
    }

    class DisplayCountdown extends TimerTask {

        public void run() {

            if (totalTime > 0) {

                refreshTextHandler.sendMessage(new Message());
                totalTime--;

            } else {
                finishQuiz();
            }

        }
    }

    public class CountDown {

        public CountDown() {

            timerTask = new Timer();
            timerTask.schedule(new DisplayCountdown(), 0, 1000);

        }

    }

    Handler refreshTextHandler = new Handler() {
        public void handleMessage(Message msg) {
            int minutes = totalTime / 60;
            int seconds = totalTime % 60;
            String minutesText = "";
            String secondsText = ""; 
            if (minutes == 0 && seconds < 30) {
                timeCountDown.setTextColor(Color.RED);
            }
            // change time
            if (minutes < 10)
                minutesText = "0" + minutes;
            else
                minutesText = "" + minutes;
            if (seconds < 10)
                secondsText = "0" + seconds;
            else
                secondsText = "" + seconds;

            timeCountDown.setText(minutesText + ":" + secondsText);

        }
    };
}
